package suery;

import java.awt.Component;
import java.awt.Container;
import java.awt.event.ContainerListener;
import java.awt.event.ContainerEvent;

import java.util.LinkedList;
import java.util.List;

/**
 * The node of component tree.
 * 
 * @author Jeky
 */
public class ComponentTreeNode implements ContainerListener {
    /**
     * Construct a new tree node.
     * 
     * @param component component to be wrapped
     */
    public ComponentTreeNode(Component component) {
        this.component = component;
        this.children = new LinkedList<ComponentTreeNode>();

        if (component instanceof Container) {
            Container container = (Container) component;
            container.addContainerListener(this);
        }
    }

    /**
     * Add child node of this node.
     * 
     * @param child child node
     */
    public void addChild(ComponentTreeNode child) {
        if (child != null) {
            children.add(child);
        }
    }

    /**
     * Remove child node of this node.
     * 
     * @param child child node
     */
    public void removeChild(ComponentTreeNode child) {
        if (child != null) {
            children.remove(child);
        }
    }

    /**
     * Get the wrapped component.
     * 
     * @return wrapped component
     */
    public Component getComponent() {
        return component;
    }

    /**
     * Get the children list of this node.
     * 
     * @return the children list of this node
     */
    public List<ComponentTreeNode> getChildren() {
        return children;
    }

    @Override
    public String toString() {
        return component == null ? "[Empty Node]" : component.toString();
    }

    @Override
    public void componentAdded(ContainerEvent e) {
        ComponentTreeNode child = findNode(e);
        addChild(child);
    }

    @Override
    public void componentRemoved(ContainerEvent e) {
        ComponentTreeNode child = findNode(e);
        removeChild(child);
    }

    private ComponentTreeNode findNode(ContainerEvent e) {
        Component child = e.getChild();
        for (ComponentTreeNode node : children) {
            if (node.getComponent() == child) {
                return node;
            }
        }

        return null;
    }

    private final Component               component;
    private final List<ComponentTreeNode> children;
}
